package com.xk.config;


import com.xk.filter.JwtAuthenticationTokenFilter;
import com.xk.handler.security.AccessDeniedHandlerImpl;
import com.xk.handler.security.AuthenticationEntryPointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * SpringSecurity的配置类
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 自定义的认证过滤器
     */
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    /**
     * 自定义 的认证失败异常处理器
     */
    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;
    /**
     * 自定义 的 授权失败异常处理器
     */
    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;
    /**
     * 替换为 BCryptPasswordEncoder
     *
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    /**
     * 配置HTTP请求安全处理
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/login").anonymous()
                .antMatchers("/hotArticleList").anonymous()
                //注销接口需要认证才能访问
                .antMatchers("/logout").authenticated();

        http    //异常处理
                .exceptionHandling()
                //添加自定义 的认证失败异常处理器
                .authenticationEntryPoint(authenticationEntryPoint)
                //添加自定义的 授权失败异常处理器
                .accessDeniedHandler(accessDeniedHandler);

        //关闭默认的注销功能
        http.logout().disable();
        //允许跨域
        http.cors();

        //把 认证过滤器 添加到 自带 登录过滤器,虽然他 已经不会进入 过滤器链里面了
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    /**
     *将AuthenticationManager对象进行公开注入容器
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


}
